import json
from typing import Optional, Literal, List, Dict, Any
from pydantic import BaseModel, Field
from .types import ClientAttachment, ToolCall

class ClientMessage(BaseModel):
    """Message model for client requests"""
    role: Literal["user", "assistant", "system"] = Field(...)
    content: str = Field(...)
    id: Optional[str] = None
    experimental_attachments: Optional[List[ClientAttachment]] = None
    tool_calls: Optional[List[ToolCall]] = None


def convert_to_openai_messages(messages: List[ClientMessage]) -> List[Dict[str, Any]]:
    """
    Convert ClientMessage objects to OpenAI API format
    
    Args:
        messages: List of ClientMessage objects
    
    Returns:
        List of message dictionaries in OpenAI API format
    """
    openai_messages = []
    
    for message in messages:
        openai_message = {
            "role": message.role,
            "content": message.content
        }
        
        # Add tool calls if present
        if message.tool_calls:
            tool_calls_list = []
            for tool_call in message.tool_calls:
                tool_calls_list.append({
                    "id": tool_call.id,
                    "type": "function",
                    "function": {
                        "name": tool_call.name,
                        "arguments": str(tool_call.arguments)
                    }
                })
            openai_message["tool_calls"] = tool_calls_list
        
        openai_messages.append(openai_message)
    
    return openai_messages